﻿using eShop.Core;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Web;

namespace eShop.UploadStrategy.LocalServer
{
    /// <summary>
    /// 本地服务器上传策略
    /// </summary>
    public partial class UploadStrategy : IUploadStrategy
    {
        /// <summary>
        /// 数据模型
        /// </summary>
        private class Pmodel
        {
            /// <summary>
            /// 仓库名称
            /// </summary>
            public string stockmc;
            /// <summary>
            /// 商品货号
            /// </summary>
            public string psn;
            /// <summary>
            /// 商品数量
            /// </summary>
            public int num = 0;
        }


        private string GetCellValue(HSSFCell cell)
        {
            if (cell == null) return "";
            string value = "";
            switch (cell.CellType)
            {
                case NPOI.SS.UserModel.CellType.Error:
                case NPOI.SS.UserModel.CellType.Blank:
                case NPOI.SS.UserModel.CellType.Unknown:
                    value = "";
                    break;
                case NPOI.SS.UserModel.CellType.Numeric:
                    value = cell.NumericCellValue.ToString();
                    break;
                case NPOI.SS.UserModel.CellType.String:
                    value = cell.StringCellValue.ToString();
                    break;
                case NPOI.SS.UserModel.CellType.Formula:
                    break;
                case NPOI.SS.UserModel.CellType.Boolean:
                    value = cell.BooleanCellValue.ToString();
                    break;
                default:
                    break;
            }
            return value;
        }

        private class DetailModel
        {
            /// <summary>
            /// 商品信息
            /// </summary>
            public string pname;
            /// <summary>
            /// 车架号
            /// </summary>
            public string vin;
            /// <summary>
            /// 发动机号
            /// </summary>
            public string gde;
            /// <summary>
            /// 自由项1
            /// </summary>
            public string conf1;
            /// <summary>
            /// 自由项2
            /// </summary>
            public string conf2;
            /// <summary>
            /// 自由项3
            /// </summary>
            public string conf3;
            /// <summary>
            /// 自由项4
            /// </summary>
            public string conf4;
            /// <summary>
            /// 自由项5
            /// </summary>
            public string conf5;
            /// <summary>
            /// 自由项6
            /// </summary>
            public string conf6;

        }


        /// <summary>
        /// 导入商品信息明细
        /// </summary>
        /// <param name="inFile"></param>
        /// <returns></returns>
        private string ImportProduceDetails(string inFile, string message)
        {
            int recnt = 0;

            try
            {
                FileStream stream = new FileStream(inFile, FileMode.Open);
                //根据路径通过已存在的excel来创建HSSFWorkbook，即整个excel文档
                HSSFWorkbook workbook = new HSSFWorkbook(stream);// new HSSFWorkbook(fullfilePath);
                                                                 //获取excel的第一个sheet
                HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
                //获取sheet的首行
                HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);
                //一行最后一个方格的编号 即总的列数
                int cellCount = headerRow.LastCellNum;
                //最后一列的标号  即总的行数
                int rowCount = sheet.LastRowNum;
                HSSFRow rowHeader = (HSSFRow)sheet.GetRow(0);
                for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                {
                    HSSFRow row = (HSSFRow)sheet.GetRow(i);
                    string vsTemp = string.Empty;
                    string vsHead = string.Empty;
                    DetailModel detail = new DetailModel();

                    detail.pname = GetCellValue((HSSFCell)row.GetCell(1));
                    if (string.IsNullOrWhiteSpace(detail.pname)) continue;
                    detail.vin = GetCellValue((HSSFCell)row.GetCell(2));
                    detail.gde = GetCellValue((HSSFCell)row.GetCell(3));
                    detail.conf1 = GetCellValue((HSSFCell)row.GetCell(4));
                    detail.conf2 = GetCellValue((HSSFCell)row.GetCell(5));
                    detail.conf3 = GetCellValue((HSSFCell)row.GetCell(6));
                    detail.conf4 = GetCellValue((HSSFCell)row.GetCell(7));
                    detail.conf5 = GetCellValue((HSSFCell)row.GetCell(8));
                    detail.conf6 = GetCellValue((HSSFCell)row.GetCell(9));
                    int pid = 0;
                    string sqlText = string.Format("select top 1 pid from bsp_products where name = '{0}'", detail.pname);
                    DbDataReader reader = RDBSHelper.ExecuteReader(System.Data.CommandType.Text, sqlText);
                    if (reader != null)
                    {
                        while (reader.Read())
                        {
                            pid = TypeHelper.ObjectToInt(reader["pid"]);
                        }
                    }
                    else
                    {
                        continue;
                    }
                    reader.Close();
                    //只有确认能找到产品的情况下，才写入数据库。
                    if (pid > 0)
                    {
                        //先删除
                        sqlText = string.Format("delete from bsp_productsdetails where pid = {0}  and vin ='{1}' and gde = '{2}'", pid, detail.vin, detail.gde);
                        RDBSHelper.ExecuteNonQuery(sqlText);
                        //开始保存
                        sqlText = string.Format(@"insert into bsp_productsdetails(pid,vin,gde,conf1,conf2,conf3,conf4,conf5,conf6)
                                                  values({0},'{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')", pid, detail.vin, detail.gde, detail.conf1, detail.conf2, detail.conf3, detail.conf4, detail.conf5, detail.conf6);
                        RDBSHelper.ExecuteNonQuery(sqlText);
                        recnt++;
                    }
                }
                stream = null;
                workbook = null;
                sheet = null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                //删除该临时文件
                if (File.Exists(inFile))
                    File.Delete(inFile);
            }
            return string.Format("{0}条数据成功导入!", recnt);
        }


        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <param name="inFile"></param>
        /// <param name="lx"></param>
        /// <returns></returns>
        private string ImportExl(string inFile, string lx)
        {
            try
            {
                FileStream stream = new FileStream(inFile, FileMode.Open);
                //根据路径通过已存在的excel来创建HSSFWorkbook，即整个excel文档
                HSSFWorkbook workbook = new HSSFWorkbook(stream);// new HSSFWorkbook(fullfilePath);
                                                                 //获取excel的第一个sheet
                HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
                //获取sheet的首行
                HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);
                //一行最后一个方格的编号 即总的列数
                int cellCount = headerRow.LastCellNum;
                //最后一列的标号  即总的行数
                int rowCount = sheet.LastRowNum;

                HSSFRow rowHeader = (HSSFRow)sheet.GetRow(0);


                for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                {
                    HSSFRow row = (HSSFRow)sheet.GetRow(i);
                    string vsTemp = string.Empty;
                    string vsHead = string.Empty;
                    Pmodel pmodel = new Pmodel();
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        vsHead = rowHeader.GetCell(j).ToString();
                        vsTemp = row.GetCell(j) == null ? "" : row.GetCell(j).ToString();
                        if (vsHead == "仓库名称")
                        {
                            pmodel.stockmc = vsTemp;
                        }
                        if (vsHead == "商品货号")
                        {
                            pmodel.psn = vsTemp;
                        }
                    }
                    //开始保存数据
                    //RDBSHelper
                    //
                }
                stream = null;
                workbook = null;
                sheet = null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                //删除该临时文件
                if (File.Exists(inFile))
                    File.Delete(inFile);
            }
            return "";
        }



        /// <summary>
        /// 下载产品明细表
        /// </summary>
        /// <returns></returns>
        public string DownLoadProducts(DataTable dt)
        {
            string url = "/ppp.xls";
            string excelUrl = System.Web.HttpContext.Current.Server.MapPath("~" + url);
            XSSFWorkbook workbook = null;
            MemoryStream ms = null;
            ISheet sheet = null;
            XSSFRow headerRow = null;
            try
            {
                workbook = new XSSFWorkbook();
                ms = new MemoryStream();
                sheet = workbook.CreateSheet();

                headerRow = (XSSFRow)sheet.CreateRow(0);
                //
                ICellStyle headStyle = workbook.CreateCellStyle();
                headStyle.Alignment = HorizontalAlignment.Center;
                IFont font = workbook.CreateFont();
                font.FontHeightInPoints = 10;
                font.Boldweight = 700;
                headStyle.SetFont(font);
                //
                foreach (DataColumn column in dt.Columns)
                {
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                    headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
                }
                //行
                int rowIndex = 1;
                foreach (DataRow row in dt.Rows)
                {
                    XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in dt.Columns)
                    {
                        //dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                        ICell newCell = dataRow.CreateCell(column.Ordinal);
                        string drValue = row[column].ToString();
                        switch (column.DataType.ToString())
                        {
                            case "System.String"://字符串类型
                                newCell.SetCellValue(drValue);
                                break;
                            case "System.DateTime"://日期类型
                                DateTime dateV;
                                DateTime.TryParse(drValue, out dateV);
                                newCell.SetCellValue(dateV);
                                break;
                            case "System.Boolean"://布尔型
                                bool boolV = false;
                                bool.TryParse(drValue, out boolV);
                                newCell.SetCellValue(boolV);
                                break;
                            case "System.Int16"://整型
                            case "System.Int32":
                            case "System.Int64":
                            case "System.Byte":
                                int intV = 0;
                                int.TryParse(drValue, out intV);
                                newCell.SetCellValue(intV);
                                break;
                            case "System.Decimal"://浮点型
                            case "System.Double":
                                double doubV = 0;
                                double.TryParse(drValue, out doubV);
                                newCell.SetCellValue(doubV);
                                break;
                            case "System.DBNull"://空值处理
                                newCell.SetCellValue("");
                                break;
                            default:
                                newCell.SetCellValue("");
                                break;
                        }
                    }
                    ++rowIndex;
                }
                //列宽自适应，只对英文和数字有效
                for (int i = 0; i <= dt.Columns.Count; ++i)
                {
                    sheet.AutoSizeColumn(i);
                }

                workbook.Write(ms);
                ms.Flush();
                using (FileStream fs = new FileStream(excelUrl, FileMode.Create, FileAccess.Write))
                {
                    byte[] data = ms.ToArray();
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                ms.Close();
                sheet = null;
                headerRow = null;
                workbook = null;
            }
            //
            return excelUrl;
        }


        /// <summary>
        /// 文件上传策略
        /// </summary>
        /// <param name="afile"></param>
        /// <returns></returns>
        public string SaveUploadFile(HttpPostedFileBase afile)
        {
            if (afile == null)
                return "-1";
            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = afile.FileName;
            string extension = Path.GetExtension(fileName);
            //if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
            //    return "-2";
            if (!ValidateHelper.IsXlsFileName(fileName))
                return "-2";
            //int fileSize = afile.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";
            string dirPath = IOHelper.GetMapPath("/upload/temp/");
            string newFileName = string.Format("f_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);//生成文件名
            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);
            afile.SaveAs(dirPath + newFileName);

            //开始处理Excel
            string vsTemp = ImportExl(dirPath + newFileName, "商品初始化");
            //
            return newFileName;
        }
        /// <summary>
        /// 导入商品明细信息表
        /// </summary>
        /// <param name="afile"></param>
        /// <returns></returns>
        public string SaveUploadFileDetails(HttpPostedFileBase afile)
        {
            if (afile == null)
                return "-1";
            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = afile.FileName;
            string extension = Path.GetExtension(fileName);
            //if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
            //    return "-2";
            if (!ValidateHelper.IsXlsFileName(fileName))
                return "-2";
            //int fileSize = afile.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";
            string dirPath = IOHelper.GetMapPath("/upload/temp/");
            string newFileName = string.Format("f_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);//生成文件名
            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);
            afile.SaveAs(dirPath + newFileName);

            //开始处理Excel
            string vsTemp = ImportProduceDetails(dirPath + newFileName, "商品明细");
            //

            return vsTemp;
        }



        /// <summary>
        /// 保存上传的用户头像
        /// </summary>
        /// <param name="avatar">用户头像</param>
        /// <returns></returns>
        public string SaveUploadUserAvatar(HttpPostedFileBase avatar)
        {
            if (avatar == null)
                return "-1";

            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = avatar.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
                return "-2";

            //int fileSize = avatar.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";

            string dirPath = IOHelper.GetMapPath("/upload/user/");
            string newFileName = string.Format("ua_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);
            string[] sizeList = StringHelper.SplitString(shopConfig.UserAvatarThumbSize);

            string sourceDirPath = dirPath + "source/";
            if (!Directory.Exists(sourceDirPath))
                Directory.CreateDirectory(sourceDirPath);

            string sourcePath = sourceDirPath + newFileName;
            avatar.SaveAs(sourcePath);

            foreach (string size in sizeList)
            {
                string thumbDirPath = string.Format("{0}thumb{1}/", dirPath, size);
                if (!Directory.Exists(thumbDirPath))
                    Directory.CreateDirectory(thumbDirPath);
                string[] widthAndHeight = StringHelper.SplitString(size, "_");
                IOHelper.GenerateThumb(sourcePath,
                                       thumbDirPath + newFileName,
                                       TypeHelper.StringToInt(widthAndHeight[0]),
                                       TypeHelper.StringToInt(widthAndHeight[1]),
                                       "H");
            }
            return newFileName;
        }

        /// <summary>
        /// 保存上传的用户等级头像
        /// </summary>
        /// <param name="avatar">用户等级头像</param>
        /// <returns></returns>
        public string SaveUploadUserRankAvatar(HttpPostedFileBase avatar)
        {
            if (avatar == null)
                return "-1";

            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = avatar.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
                return "-2";

            //int fileSize = avatar.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";

            string dirPath = IOHelper.GetMapPath("/upload/userrank/");
            string newFileName = string.Format("ura_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);
            string[] sizeList = StringHelper.SplitString(shopConfig.UserRankAvatarThumbSize);

            string sourceDirPath = dirPath + "source/";
            if (!Directory.Exists(sourceDirPath))
                Directory.CreateDirectory(sourceDirPath);

            string sourcePath = sourceDirPath + newFileName;
            avatar.SaveAs(sourcePath);

            foreach (string size in sizeList)
            {
                string thumbDirPath = string.Format("{0}thumb{1}/", dirPath, size);
                if (!Directory.Exists(thumbDirPath))
                    Directory.CreateDirectory(thumbDirPath);
                string[] widthAndHeight = StringHelper.SplitString(size, "_");
                IOHelper.GenerateThumb(sourcePath,
                                       thumbDirPath + newFileName,
                                       TypeHelper.StringToInt(widthAndHeight[0]),
                                       TypeHelper.StringToInt(widthAndHeight[1]),
                                       "H");
            }
            return newFileName;
        }

        /// <summary>
        /// 保存上传的品牌logo
        /// </summary>
        /// <param name="logo">品牌logo</param>
        /// <returns></returns>
        public string SaveUploadBrandLogo(HttpPostedFileBase logo)
        {
            if (logo == null)
                return "-1";

            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = logo.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
                return "-2";

            //int fileSize = logo.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";

            string dirPath = IOHelper.GetMapPath("/upload/brand/");
            string newFileName = string.Format("b_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);
            string[] sizeList = StringHelper.SplitString(shopConfig.BrandThumbSize);

            string sourceDirPath = dirPath + "source/";
            if (!Directory.Exists(sourceDirPath))
                Directory.CreateDirectory(sourceDirPath);

            string sourcePath = sourceDirPath + newFileName;
            logo.SaveAs(sourcePath);

            foreach (string size in sizeList)
            {
                string thumbDirPath = string.Format("{0}thumb{1}/", dirPath, size);
                if (!Directory.Exists(thumbDirPath))
                    Directory.CreateDirectory(thumbDirPath);
                string[] widthAndHeight = StringHelper.SplitString(size, "_");
                IOHelper.GenerateThumb(sourcePath,
                                       thumbDirPath + newFileName,
                                       TypeHelper.StringToInt(widthAndHeight[0]),
                                       TypeHelper.StringToInt(widthAndHeight[1]),
                                       "H");
            }
            return newFileName;
        }

        /// <summary>
        /// 保存新闻编辑器中的图片
        /// </summary>
        /// <param name="image">新闻图片</param>
        /// <returns></returns>
        public string SaveNewsEditorImage(HttpPostedFileBase image)
        {
            if (image == null)
                return "-1";

            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = image.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
                return "-2";

            //int fileSize = image.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";

            string dirPath = IOHelper.GetMapPath("/upload/news/");
            string newFileName = string.Format("n_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);//生成文件名

            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);
            image.SaveAs(dirPath + newFileName);

            return newFileName;
        }

        /// <summary>
        /// 保存帮助编辑器中的图片
        /// </summary>
        /// <param name="image">帮助图片</param>
        /// <returns></returns>
        public string SaveHelpEditorImage(HttpPostedFileBase image)
        {
            if (image == null)
                return "-1";

            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = image.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
                return "-2";

            //int fileSize = image.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";

            string dirPath = IOHelper.GetMapPath("/upload/help/");
            string newFileName = string.Format("h_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);//生成文件名

            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);
            image.SaveAs(dirPath + newFileName);

            return newFileName;
        }

        /// <summary>
        /// 保存商品编辑器中的图片
        /// </summary>
        /// <param name="image">商品图片</param>
        /// <returns></returns>
        public string SaveProductEditorImage(HttpPostedFileBase image)
        {
            if (image == null)
                return "-1";

            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = image.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
                return "-2";

            //int fileSize = image.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";

            string dirPath = IOHelper.GetMapPath("/upload/product/editor/");
            string newFileName = string.Format("pe_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);//生成文件名

            string sourceDirPath = dirPath + "source/";
            if (!Directory.Exists(sourceDirPath))
                Directory.CreateDirectory(sourceDirPath);
            string sourcePath = sourceDirPath + newFileName;
            image.SaveAs(sourcePath);

            string path = dirPath + newFileName;
            if (shopConfig.WatermarkType == 1)//文字水印
            {
                IOHelper.GenerateTextWatermark(sourcePath, path, shopConfig.WatermarkText, shopConfig.WatermarkTextSize, shopConfig.WatermarkTextFont, shopConfig.WatermarkPosition, shopConfig.WatermarkQuality);
            }
            else if (shopConfig.WatermarkType == 2)//图片水印
            {
                string watermarkPath = IOHelper.GetMapPath("/watermarks/" + shopConfig.WatermarkImg);
                IOHelper.GenerateImageWatermark(sourcePath, watermarkPath, path, shopConfig.WatermarkPosition, shopConfig.WatermarkImgOpacity, shopConfig.WatermarkQuality);
            }
            else
            {
                image.SaveAs(path);
            }

            return newFileName;
        }

        /// <summary>
        /// 保存上传的商品图片
        /// </summary>
        /// <param name="image">商品图片</param>
        /// <returns></returns>
        public string SaveUplaodProductImage(HttpPostedFileBase image)
        {
            if (image == null)
                return "-1";

            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = image.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
                return "-2";

            //int fileSize = image.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";

            string dirPath = IOHelper.GetMapPath("/upload/product/show/");
            string name = "ps_" + DateTime.Now.ToString("yyMMddHHmmssfffffff");
            string newFileName = name + extension;
            string[] sizeList = StringHelper.SplitString(shopConfig.ProductShowThumbSize);

            string sourceDirPath = string.Format("{0}source/", dirPath);
            if (!Directory.Exists(sourceDirPath))
                Directory.CreateDirectory(sourceDirPath);
            string sourcePath = sourceDirPath + newFileName;
            image.SaveAs(sourcePath);

            if (shopConfig.WatermarkType == 1)//文字水印
            {
                string path = string.Format("{0}{1}_text{2}", sourceDirPath, name, extension);
                IOHelper.GenerateTextWatermark(sourcePath, path, shopConfig.WatermarkText, shopConfig.WatermarkTextSize, shopConfig.WatermarkTextFont, shopConfig.WatermarkPosition, shopConfig.WatermarkQuality);
                sourcePath = path;
            }
            else if (shopConfig.WatermarkType == 2)//图片水印
            {
                string path = string.Format("{0}{1}_img{2}", sourceDirPath, name, extension);
                string watermarkPath = IOHelper.GetMapPath("/watermarks/" + shopConfig.WatermarkImg);
                IOHelper.GenerateImageWatermark(sourcePath, watermarkPath, path, shopConfig.WatermarkPosition, shopConfig.WatermarkImgOpacity, shopConfig.WatermarkQuality);
                sourcePath = path;
            }

            foreach (string size in sizeList)
            {
                string thumbDirPath = string.Format("{0}thumb{1}/", dirPath, size);
                if (!Directory.Exists(thumbDirPath))
                    Directory.CreateDirectory(thumbDirPath);
                string[] widthAndHeight = StringHelper.SplitString(size, "_");
                IOHelper.GenerateThumb(sourcePath,
                                       thumbDirPath + newFileName,
                                       TypeHelper.StringToInt(widthAndHeight[0]),
                                       TypeHelper.StringToInt(widthAndHeight[1]),
                                       "H");
            }
            return newFileName;
        }

        /// <summary>
        /// 保存上传的广告图片
        /// </summary>
        /// <param name="image">广告图片</param>
        /// <returns></returns>
        public string SaveUploadAdvertImage(HttpPostedFileBase image)
        {
            if (image == null)
                return "-1";

            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = image.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
                return "-2";

            //int fileSize = image.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";

            string dirPath = IOHelper.GetMapPath("/upload/adv/");
            string newFileName = string.Format("ad_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);//生成文件名

            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);
            image.SaveAs(dirPath + newFileName);

            return newFileName;
        }

        /// <summary>
        /// 保存上传的友情链接Logo
        /// </summary>
        /// <param name="logo">友情链接logo</param>
        /// <returns></returns>
        public string SaveUploadFriendLinkLogo(HttpPostedFileBase logo)
        {
            if (logo == null)
                return "-1";

            ShopConfigInfo shopConfig = BSPConfig.ShopConfig;

            string fileName = logo.FileName;
            string extension = Path.GetExtension(fileName);
            if (!ValidateHelper.IsImgFileName(fileName) || !CommonHelper.IsInArray(extension, shopConfig.UploadImgType))
                return "-2";

            //int fileSize = logo.ContentLength;
            //if (fileSize > shopConfig.UploadImgSize)
            //    return "-3";

            string dirPath = IOHelper.GetMapPath("/upload/friendlink/");
            string newFileName = string.Format("fr_{0}{1}", DateTime.Now.ToString("yyMMddHHmmssfffffff"), extension);//生成文件名

            if (!Directory.Exists(dirPath))
                Directory.CreateDirectory(dirPath);
            logo.SaveAs(dirPath + newFileName);

            return newFileName;
        }
    }
}
